import requests
from lxml import html

def spider(sn,goods_list):
    """ 爬取京东红楼梦 """

    headers = {
        'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Mobile Safari/537.36 Edg/86.0.622.63',

    }



    url = 'https://search.jd.com/Search?keyword={0}'.format(sn)

    #获取html文档
    resp = requests.get(url,headers = headers)
    print(resp.encoding)
    html_doc = resp.text
    #获取xpath对象
    selector = html.fromstring(html_doc)
    print(selector)
    #找到列表的集合
    ul_list = selector.xpath('//div[@id="J_goodsList"]/ul/li')
    print(len(ul_list))
    # #解析对应的内容，标题，价格，链接

    for i in ul_list:

        #标题
        title = i.xpath('div/div[@class="p-name"]/a/em/text()')
        if(len(title)==0):
           print("攻打手机打开",len(title))
        else:
            print(title[0])
        #价格
        price = i.xpath('div/div[@class="p-price"]/strong/i/text()')
        print(price[0])

        #链接
        herf = i.xpath('div/div[@class="p-img"]/a/@href')
        print(herf)

        #添加数据到list

        # goods_list.append({
        #     'title': title[0],
        #     'price': price[0],
        #     'href': herf[0]
        # })

if __name__ == '__main__':
    spider("9787020002207",[])